import {
    combineReducers
} from 'redux';

import {
    ADD_TODO,
    COMPLETED_TODO,
    REMOVE_TODO,
    TOGGLE_ALL_TODO,
    SET_VISIBILITY_FILTER,
    VisibilityFilters
} from '../actions/TodoAction';

let storeTodo = localStorage['todos'] || {
    visibilityFilter: VisibilityFilters.SHOW_ALL,
    todos: []
};
if (storeTodo && typeof storeTodo === 'string') {
    storeTodo = JSON.parse(storeTodo);
}

function visibilityFilter(state = storeTodo.visibilityFilter, action) {
    switch (action.type) {
        case SET_VISIBILITY_FILTER:
            return action.filter;
        default:
            return state;
    }
}

function todos(state = storeTodo.todos, action) {
    switch (action.type) {
        case ADD_TODO:
            return [{
                text: action.text,
                todoId: Math.random().toString(16).substr(2),
                completed: false
            }, ...state];
        case COMPLETED_TODO:
            let todos = [];
            state.map((todo) => {
                if (todo.todoId === action.todoId) {
                    todo.completed = !todo.completed;
                }
                todos.push(todo);
            })
            return todos;
        case REMOVE_TODO:
            return state.filter((todo) => {
                return todo.todoId !== action.todoId;
            });
        case TOGGLE_ALL_TODO:
            return state.map((todo) => {
                todo.completed = action.completed
                return todo;
            })
        default:
            return state;
    }
}

const todoApp = combineReducers({
    todos,
    visibilityFilter
});
export default todoApp;